import { composeTree, flattenTree, groupBy, uid } from '@/utils';
import React, { createContext } from 'react';

export const sortTreeByHasChild = (treeData) => (
  treeData.forEach((item) => {
    if (item?.children?.length) item.children = sortTreeByHasChild(item.children);
  }),
  treeData.sort((a, b) => {
    const aHasChild = a.children?.length > 0;
    const bHasChild = b.children?.length > 0;
    if (aHasChild === bHasChild) return 0;
    if (aHasChild) return -1;
    return 1;
  })
);

export const composeTreeByProp = (list, propList = []) => {
  //  $prop: '层级属性名'; $value: '层级属性值值'; $key: '层级节点key'
  const keyMap = {}; // { "$prop.$value": "$key" }

  const [lastProp] = propList.splice(-1, 1);
  if (!lastProp) return list;

  const flatList = list.reduce((ret, item) => {
    let key = item.id;
    item.key = item.id;
    item.title = item[lastProp];
    item.parentKey = propList.reduce((parentKey, prop) => {
      const value = item[prop];
      if (!value || value === '0') return parentKey;
      key += `.${value}`;

      let currentParentKey = keyMap[`${prop}.${value}`];

      if (!currentParentKey) {
        currentParentKey = keyMap[`${prop}.${value}`] = key;
        ret.push({ ...item, key, parentKey, groupBy: prop, title: value });
      }

      return currentParentKey;
    }, '0');
    item.groupBy = lastProp;

    ret.push(item);
    return ret;
  }, []);

  return composeTree(flatList, { parentKey: 'parentKey', key: 'key', rootId: '0' });
};

export const dataToForm = (responseData) => {
  if (!responseData?.length) return {};

  const { productCode, productName, companyName } = responseData[0];

  // diseaseType 第一层标题；illnessDesc 第一层描述；diseaseGroup 第二层标题 (第二层不分组的情况下为"0"）
  const treeList = composeTreeByProp(responseData, ['diseaseType', 'diseaseGroup', 'diseaseName']);

  return [{ productCode, productName, companyName }, treeList];
};

export const formToData = (formData, treeList) => {
  const flattenList = flattenTree(treeList, {
    includeParent: false,
    map: (node, depth, parent) => ({
      ...formData,
      id: node.id ?? null,
      diseaseType: node?.diseaseType ?? parent?.diseaseType,
      illnessDesc: node?.illnessDesc ?? parent?.illnessDesc,
      diseaseGroup: node?.diseaseGroup ?? parent?.diseaseGroup ?? '0',
      [node.groupBy]: node[node.groupBy] ?? '0',
      diseaseName: node.diseaseName,
      diseaseDesc: node.diseaseDesc,
    }),
  });

  console.log(flattenList);

  return flattenList;
};

export const ItemCtx = createContext({ selected: null, parent: null, onAdd: null, onRemove: null });

export const createItem = (groupBy, parentKey = '0') => ({
  id: null,
  key: uid(),
  groupBy,
  parentKey,
  diseaseType: null,
  illnessDesc: null,
  diseaseGroup: null,
  diseaseName: null,
  diseaseDesc: null,
  [groupBy]: '未命名',
  title: '未命名',
  children: [],
});

export const getKeyPath = (treeList, currentKey) => {
  const flatList = flattenTree(treeList);
  const byKey = groupBy(flatList, 'key');

  let current = flatList.find((t) => t.key === currentKey);
  const keyList = [currentKey];

  console.log({ current, currentKey, flatList, treeList });

  while (current.parentKey !== '0') {
    current = byKey[current.parentKey][0];
    keyList.unshift(current.key);
  }

  let next = treeList;
  const keyPath = [];
  while (keyList.length) {
    const key = keyList.shift();
    let n = next.find((t) => t.key === key);
    if (!n) break;

    keyPath.push(next.indexOf(n), 'children');
    next = n.children;
  }

  keyPath.splice(-1, 1);
  return keyPath;
};
